"""Endpoints for Shop TMS tracking dashboard."""

from __future__ import annotations

from typing import Any, Dict, List

import frappe
from frappe import _


def _ensure_authenticated() -> None:
    if frappe.session.user == "Guest":
        frappe.throw(_('Please log in to view shop shipments.'), frappe.PermissionError)


def _user_can_read_company(company: str) -> bool:
    try:
        return bool(frappe.has_permission("Company", "read", company))
    except Exception:
        return False


@frappe.whitelist()
def get_shop_shipments(page: int | None = None, page_size: int | None = None) -> Dict[str, Any]:
    """Return active shipments (orders with tracking numbers) for the current user.

    注意：
    - 统计 & 状态判定都基于 `Logistics Order Inst`（物流订单实例表）
    - 仍联接 `Sales Order` 获取客户、店铺等展示字段
    """
    _ensure_authenticated()

    # 解析分页参数
    try:
        page = int(page or 1)
    except Exception:
        page = 1
    if page <= 0:
        page = 1

    try:
        page_size = int(page_size or 20)
    except Exception:
        page_size = 20
    if page_size <= 0:
        page_size = 20
    if page_size > 200:
        page_size = 200

    # 按当前用户的 User Permission 过滤公司；若未配置则回退到默认公司
    user_perms = frappe.get_all(
        "User Permission",
        fields=["for_value"],
        filters={
            "user": frappe.session.user,
            "allow": "Company",
        },
        limit_page_length=0,
    )
    companies = [row["for_value"] for row in user_perms if row.get("for_value")]

    if not companies:
        # 回退到系统/站点默认公司（与首页统计逻辑保持一致）
        default_company = (
            frappe.get_value("User Default", {"user": frappe.session.user, "defkey": "company"}, "defvalue")
            or frappe.db.get_default("company")
            or frappe.db.get_single_value("Global Defaults", "default_company")
        )
        if default_company:
            companies = [default_company]

    companies = sorted(set(companies))

    if not companies:
        return {
            "success": True,
            "shipments": [],
            "total": 0,
            "page": page,
            "page_size": page_size,
        }

    companies_tuple = tuple(companies)

    # 先统计总数
    total = frappe.db.sql(
        """
        SELECT COUNT(*)
        FROM `tabLogistics Order Inst`
        WHERE
            company IN %(companies)s
            AND (
                IFNULL(waybill_number, '') != ''
                OR IFNULL(tracking_number, '') != ''
            )
        """,
        {"companies": companies_tuple},
    )[0][0]

    offset = (page - 1) * page_size

    # 仅基于 Logistics Order Inst 查询（不再关联 Sales Order）
    # 仅返回非计费相关字段，避免将费用明细透传给前端
    rows = frappe.db.sql(
        """
        SELECT
            name                 AS los_name,
            sales_order          AS sales_order,
            company              AS company,
            waybill_number       AS waybill_number,
            tracking_number      AS tracking_number,
            yt_product_code      AS yt_product_code,
            destination_country  AS destination_country,
            pieces               AS pieces,
            actual_weight        AS actual_weight,
            charge_weight        AS charge_weight,
            warehouse_weight     AS warehouse_weight,
            recipient_name       AS recipient_name,
            recipient_phone      AS recipient_phone,
            recipient_email      AS recipient_email,
            recipient_country    AS recipient_country,
            recipient_state      AS recipient_state,
            recipient_city       AS recipient_city,
            recipient_address    AS recipient_address,
            creation_time        AS creation_time,
            time_of_receipt      AS time_of_receipt,
            delivery_time        AS delivery_time,
            cancel_time          AS cancel_time,
            return_time          AS return_time,
            pod_url              AS pod_url,
            pod_time             AS pod_time,
            logistics_status_code AS logistics_status_code,
            track_node_code      AS track_node_code,
            last_event_text      AS last_event_text,
            last_event_time      AS last_event_time,
            issue                AS issue,
            issue_raised_at      AS issue_raised_at,
            issue_status         AS issue_status,
            track_last_updated   AS track_last_updated,
            track_history_json   AS track_history_json
        FROM `tabLogistics Order Inst`
        WHERE
            company IN %(companies)s
            AND (
                IFNULL(waybill_number, '') != ''
                OR IFNULL(tracking_number, '') != ''
            )
        ORDER BY track_last_updated DESC, creation_time DESC
        LIMIT %(page_size)s OFFSET %(offset)s
        """,
        {
            "companies": companies_tuple,
            "page_size": page_size,
            "offset": offset,
        },
        as_dict=True,
    )

    return {
        "success": True,
        "shipments": rows,
        "total": int(total or 0),
        "page": page,
        "page_size": page_size,
    }
